<template>
  <div class="advanced-filter">
    <el-card class="filter-card" :body-style="{ padding: '20px' }">
      <div class="filter-header">
        <div class="filter-title">
          <el-icon><Filter /></el-icon>
          <span>高级筛选</span>
        </div>
        <div class="filter-actions">
          <el-button-group>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-button-group>
          <el-dropdown @command="handleCommand">
            <el-button>
              <el-icon><More /></el-icon>
              更多操作
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="save">保存筛选条件</el-dropdown-item>
                <el-dropdown-item command="load">加载已保存</el-dropdown-item>
                <el-dropdown-item command="clear">清除已保存</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 快速筛选标签 -->
      <div class="quick-filter-tags" v-if="quickFilters.length > 0">
        <div class="quick-filter-title">快速筛选：</div>
        <div class="quick-filter-content">
          <el-tag
            v-for="(tag, index) in quickFilters"
            :key="index"
            :type="tag.type || 'info'"
            class="quick-filter-tag"
            @click="applyQuickFilter(tag)"
            :effect="tag.active ? 'dark' : 'plain'"
          >
            {{ tag.label }}
          </el-tag>
        </div>
      </div>

      <div class="filter-content">
        <el-form :model="filterForm" label-width="100px" class="filter-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(item, index) in filterItems" :key="index">
              <el-form-item :label="item.label">
                <!-- 文本输入 -->
                <el-input
                  v-if="item.type === 'text'"
                  v-model="filterForm[item.prop]"
                  :placeholder="item.placeholder"
                  clearable
                />

                <!-- 数字输入 -->
                <el-input-number
                  v-else-if="item.type === 'number'"
                  v-model="filterForm[item.prop]"
                  :min="item.min"
                  :max="item.max"
                  :step="item.step"
                  :precision="item.precision"
                  clearable
                />

                <!-- 日期选择 -->
                <el-date-picker
                  v-else-if="item.type === 'date'"
                  v-model="filterForm[item.prop]"
                  :type="item.dateType || 'date'"
                  :placeholder="item.placeholder"
                  :format="item.format"
                  :value-format="item.valueFormat"
                  clearable
                />

                <!-- 选择器 -->
                <el-select
                  v-else-if="item.type === 'select'"
                  v-model="filterForm[item.prop]"
                  :placeholder="item.placeholder"
                  :multiple="item.multiple"
                  :clearable="true"
                  filterable
                >
                  <el-option
                    v-for="option in item.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>

                <!-- 开关 -->
                <el-switch
                  v-else-if="item.type === 'switch'"
                  v-model="filterForm[item.prop]"
                  :active-text="item.activeText"
                  :inactive-text="item.inactiveText"
                />

                <!-- 职业选择器 -->
                <el-select
                  v-else-if="item.type === 'profession'"
                  v-model="filterForm[item.prop]"
                  :placeholder="item.placeholder"
                  :multiple="item.multiple"
                  :clearable="true"
                  filterable
                >
                  <el-option-group
                    v-for="group in professionOptions"
                    :key="group.label"
                    :label="group.label"
                  >
                    <el-option
                      v-for="option in group.options"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-option-group>
                </el-select>

                <!-- 难度选择器 -->
                <el-select
                  v-else-if="item.type === 'difficulty'"
                  v-model="filterForm[item.prop]"
                  :placeholder="item.placeholder"
                  :multiple="item.multiple"
                  :clearable="true"
                >
                  <el-option
                    v-for="option in difficultyOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  >
                    <span class="difficulty-option">
                      <span :class="['difficulty-dot', option.value]"></span>
                      {{ option.label }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 高级筛选区域 -->
      <div class="advanced-filter-section" v-if="showAdvanced">
        <el-divider>高级筛选</el-divider>
        <div class="advanced-rules">
          <div v-for="(rule, index) in advancedRules" :key="index" class="rule-item">
            <el-select v-model="rule.field" placeholder="选择字段" style="width: 150px">
              <el-option
                v-for="item in filterItems"
                :key="item.prop"
                :label="item.label"
                :value="item.prop"
              />
            </el-select>
            <el-select v-model="rule.operator" placeholder="选择运算符" style="width: 120px">
              <el-option label="等于" value="=" />
              <el-option label="不等于" value="!=" />
              <el-option label="大于" value=">" />
              <el-option label="小于" value="<" />
              <el-option label="包含" value="include" />
              <el-option label="不包含" value="notinclude" />
            </el-select>
            <el-input v-model="rule.value" placeholder="输入值" style="width: 200px" />
            <el-button type="danger" @click="removeRule(index)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          <el-button type="primary" @click="addRule">
            <el-icon><Plus /></el-icon>
            添加规则
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 保存筛选条件对话框 -->
    <el-dialog v-model="saveDialogVisible" title="保存筛选条件" width="400px">
      <el-form :model="saveForm" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="saveForm.name" placeholder="请输入筛选条件名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="saveForm.description"
            type="textarea"
            placeholder="请输入筛选条件描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="saveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFilter">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加载筛选条件对话框 -->
    <el-dialog v-model="loadDialogVisible" title="加载筛选条件" width="600px">
      <el-table :data="savedFilters" style="width: 100%">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" link @click="loadFilter(scope.row)">
              加载
            </el-button>
            <el-button type="danger" link @click="deleteFilter(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Filter, Search, Refresh, More, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  // 筛选项配置
  items: {
    type: Array,
    default: () => []
  },
  // 是否显示高级筛选
  showAdvanced: {
    type: Boolean,
    default: true
  },
  // 快速筛选标签
  quickFilters: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['search', 'reset'])

// 筛选表单数据
const filterForm = reactive({})
const filterItems = ref(props.items)

// 高级筛选规则
const advancedRules = ref([])

// 对话框控制
const saveDialogVisible = ref(false)
const loadDialogVisible = ref(false)
const saveForm = reactive({
  name: '',
  description: ''
})

// 已保存的筛选条件
const savedFilters = ref([])

// 职业选项
const professionOptions = [
  {
    label: '技术类',
    options: [
      { label: '前端开发', value: 'frontend' },
      { label: '后端开发', value: 'backend' },
      { label: '全栈开发', value: 'fullstack' },
      { label: '移动开发', value: 'mobile' },
      { label: '算法工程师', value: 'algorithm' },
      { label: '数据工程师', value: 'data' },
      { label: '运维工程师', value: 'ops' },
      { label: '测试工程师', value: 'test' }
    ]
  },
  {
    label: '设计类',
    options: [
      { label: 'UI设计师', value: 'ui' },
      { label: 'UX设计师', value: 'ux' },
      { label: '平面设计师', value: 'graphic' },
      { label: '交互设计师', value: 'interaction' }
    ]
  },
  {
    label: '产品类',
    options: [
      { label: '产品经理', value: 'pm' },
      { label: '产品运营', value: 'operation' },
      { label: '数据分析师', value: 'analyst' }
    ]
  },
  {
    label: '管理类',
    options: [
      { label: '项目经理', value: 'project_manager' },
      { label: '技术主管', value: 'tech_lead' },
      { label: '部门经理', value: 'department_manager' }
    ]
  }
]

// 难度选项
const difficultyOptions = [
  { label: '入门', value: 'beginner' },
  { label: '简单', value: 'easy' },
  { label: '中等', value: 'medium' },
  { label: '困难', value: 'hard' },
  { label: '专家', value: 'expert' }
]

// 初始化表单数据
const initFormData = () => {
  filterItems.value.forEach(item => {
    filterForm[item.prop] = item.defaultValue || null
  })
}

// 处理搜索
const handleSearch = () => {
  const searchData = {
    ...filterForm,
    advancedRules: advancedRules.value
  }
  emit('search', searchData)
}

// 处理重置
const handleReset = () => {
  initFormData()
  advancedRules.value = []
  emit('reset')
}

// 应用快速筛选
const applyQuickFilter = (tag) => {
  // 切换标签激活状态
  tag.active = !tag.active
  
  // 应用筛选条件
  if (tag.active) {
    if (tag.filter) {
      Object.assign(filterForm, tag.filter)
    }
  } else {
    // 如果取消选中，重置相关字段
    if (tag.resetFields) {
      tag.resetFields.forEach(field => {
        filterForm[field] = null
      })
    }
  }
}

// 添加高级筛选规则
const addRule = () => {
  advancedRules.value.push({
    field: '',
    operator: '=',
    value: ''
  })
}

// 删除高级筛选规则
const removeRule = (index) => {
  advancedRules.value.splice(index, 1)
}

// 处理更多操作
const handleCommand = (command) => {
  switch (command) {
    case 'save':
      saveDialogVisible.value = true
      break
    case 'load':
      loadDialogVisible.value = true
      break
    case 'clear':
      ElMessageBox.confirm('确定要清除所有已保存的筛选条件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        savedFilters.value = []
        ElMessage.success('已清除所有筛选条件')
      })
      break
  }
}

// 保存筛选条件
const saveFilter = () => {
  if (!saveForm.name) {
    ElMessage.warning('请输入筛选条件名称')
    return
  }

  const filter = {
    ...saveForm,
    filterData: { ...filterForm },
    advancedRules: [...advancedRules.value],
    createTime: new Date().toLocaleString()
  }

  savedFilters.value.push(filter)
  saveDialogVisible.value = false
  ElMessage.success('保存成功')
}

// 加载筛选条件
const loadFilter = (filter) => {
  Object.assign(filterForm, filter.filterData)
  advancedRules.value = [...filter.advancedRules]
  loadDialogVisible.value = false
  ElMessage.success('加载成功')
}

// 删除筛选条件
const deleteFilter = (filter) => {
  const index = savedFilters.value.indexOf(filter)
  if (index > -1) {
    savedFilters.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 初始化
initFormData()
</script>

<style scoped>
.advanced-filter {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.filter-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.quick-filter-tags {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.quick-filter-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.quick-filter-content {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-filter-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.quick-filter-tag:hover {
  transform: translateY(-2px);
}

.filter-content {
  margin-bottom: 20px;
}

.advanced-filter-section {
  margin-top: 20px;
}

.advanced-rules {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rule-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.difficulty-option {
  display: flex;
  align-items: center;
}

.difficulty-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}

.difficulty-dot.beginner {
  background-color: #67c23a;
}

.difficulty-dot.easy {
  background-color: #409eff;
}

.difficulty-dot.medium {
  background-color: #e6a23c;
}

.difficulty-dot.hard {
  background-color: #f56c6c;
}

.difficulty-dot.expert {
  background-color: #909399;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-option-group__title) {
  font-weight: bold;
  color: #409eff;
}
</style> 